package com.expertria.glex.view;

import com.expertria.glex.view.layout.ILayout;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
 
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.Widget;
 
/**
 * A List renders a set of data according to its layout and its renderer
 * However, List implements ISelectable which has one or many elements selectable
 * This List does not have a scroll and will have infinite height.
 * To use a List with a scrollbar, use {ScrollList}
 * @author hushunjie
 *
 */
public class List extends Repeater implements  IList {

	
	private Widget selectedWidget;
	
	public static class ListEvent
	{
		public static final String //
		CHANGE = "CHANGE", //
		SELECTION_CHANGE = "SELECTION_CHANGE"; //
	}
	
	public @UiConstructor List(ILayout layout)
	{
		super(layout)	;
	}

	private void selectionChange(Widget w)
	{
		w.addStyleName("selected");
		
		if(selectedWidget != null) selectedWidget.removeStyleName("selected");
		selectedWidget = w;
		
		this.dispatch(ListEvent. CHANGE, selectedWidget);
		this.dispatch( ListEvent. SELECTION_CHANGE,  getWidgetIndex(selectedWidget));
	}
	
	public void setSelectedIndex(int i)
	{
		selectionChange(this.getWidget(i));
	}
	
	@Override
	public int getSelectedIndex() {
	 
		return getWidgetIndex(selectedWidget);
	}
	
	
	@Override
	public void addWidget(Widget child) {
		
		
		super.addWidget(child);
		
		if(child instanceof HasClickHandlers)
		{
			HasClickHandlers c = (HasClickHandlers) child;
			c.addClickHandler(onWidgetClick);
		}
	}
	
	 
	private final ClickHandler onWidgetClick = new ClickHandler() {
		
		@Override
		public void onClick(ClickEvent event) {
			
			Widget lbl = (Widget) event.getSource();
			if(!lbl.equals(selectedWidget))
			{				
				selectionChange(lbl);
			}
		}
	};
}
